package com.nie.mybatisPlus.generator.system.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.nie.mybatisPlus.generator.system.context.BaseContextHandler;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * mybatis +配置
 *
 * @author nie_cq
 * @date 2022/11/18
 */
@Configuration
@Slf4j
public class MybatisPlusConfig {

    private static final List<String> FILTER_TABLE_LIST = new ArrayList<>();

    private static final String TENANT_ID_COLUMN_NAME = "tenant_id";
    static{
        FILTER_TABLE_LIST.add("tb_master_tenant");
    }

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {
            @Override
            public Expression getTenantId() {
                Long tenantId = Long.valueOf(BaseContextHandler.getTenantId());
                return new LongValue(BaseContextHandler.getTenantId());
            }

            @Override
            public String getTenantIdColumn() {
                return TENANT_ID_COLUMN_NAME;
            }

            @Override
            public boolean ignoreTable(String tableName) {
                return FILTER_TABLE_LIST.stream().anyMatch(x -> x.contains(tableName));
            }
        }));
        return interceptor;
    }
}
